<template>
  <div class="setting-container">
    <div class="app-container">
      <!-- 卡片组件 -->
      <el-card class="box-card">
        <!-- 使用 Tabs 组件完成标签页布局 -->
        <el-tabs v-loading="loading" v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="角色管理" name="first" class="tab-pane">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="addRole()">新增角色</el-button>
            </el-row>
            <!-- 使用 Table 组件实现用户角色的渲染 -->
            <el-table :data="nowRolesList" border style="width: 100%">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column label="角色名" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="setRoles(scope.row)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRoles(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRoles(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination :page-sizes="[2,3,4, 5]" :current-page="query.page" :page-size="query.pagesize"
              layout="total,sizes, prev, pager, next, jumper" :total="query.total" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </el-tab-pane>
          <el-tab-pane name="second" label="公司信息" class="tab-pane">
            <el-alert title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改" type="info" show-icon :closable="false" />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input disabled v-model="formData.name" style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input disabled v-model="formData.companyAddress" style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input disabled v-model="formData.mailbox" style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" v-model="formData.remarks" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <el-dialog :title="is_add? '新增角色':'编辑角色'" :visible="dialogFormVisible" @close="btnCanCel">
          <el-form ref="formName" :model="editorForm" :rules="rules">
            <el-form-item prop="name" label="角色名称" :label-width="formLabelWidth">
              <el-input v-model="editorForm.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" :label-width="formLabelWidth">
              <el-input v-model="editorForm.description" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="btnCanCel">取 消</el-button>
            <el-button type="primary" @click="btnSubmit">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 分配权限弹层 -->
        <el-dialog title="分配权限" :visible="dialogautisible" @close="CancelRoleBtn">
          <el-tree ref="Roles" :data="permData" show-checkbox node-key="id" default-expand-all :check-strictly="true"
            :default-checked-keys="selectData" :props="defaultProps">
          </el-tree>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button type="primary" @click="btn_Role_Ok">确认</el-button>
              <el-button type="info" @click="CancelRoleBtn">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
  import {
    getRoleListAPI, getenterpriseIdAPI, deleteRoleAPI, updateRoleAPI,
    getRoleIdAPI, addRoleAPI, getPermissionListAPI, assignPermAPI
  } from '@/api'
  import { mapGetters } from 'vuex'
  import { transTree } from '@/utils'
  export default {
    data () {
      return {
        loading: false,
        activeName: 'first',
        query: {
          page: 1, // 当前页面
          pagesize: 4, // 页面显示的条数
          total: 0 // 角色数据总条数
        },
        rolesList: [], // 角色列表
        nowRolesList: [], //当前页面角色
        formData: {}, // 公司信息对象
        dialogFormVisible: false,
        permData: [],  //权限数据
        selectData: [],// 已选中的权限数据
        roleId: null,
        defaultProps: {
          label: 'name'
        },  //显示对象的名称和子属性的名称
        dialogautisible: false,  //分配权限弹层
        editorForm: {
          name: '',
          description: ''
        }, //单个角色信息
        formLabelWidth: '120px',
        rules: {
          name: [{ required: true, trigger: 'blur', message: '角色名称不能为空' }]
        },
        is_add: false //是否新增角色
      }
    },
    computed: {
      ...mapGetters['companyId']
    },
    created () {
      this.getRoles()
    },
    methods: {
      // 分配权限
      async setRoles (row) {
        this.dialogautisible = true
        this.roleId = row.id
        const { permIds } = await getRoleIdAPI(row.id)
        this.selectData = permIds
        this.permData = transTree(await getPermissionListAPI(), '0')
      },
      CancelRoleBtn () {
        this.dialogautisible = false
      },
      async btn_Role_Ok () {
        this.selectData = this.$refs.Roles.getCheckedKeys()
        await assignPermAPI({ id: this.roleId, permIds: this.selectData })
        this.$message.success('权限更新成功')
        this.dialogautisible = false
      },
      // 获取所有角色
      async getRoles () {
        const { rows, total } = await getRoleListAPI(this.query.page, this.query.pagesize)
        this.query.total = total
        this.rolesList = rows
        this.paging()
      },
      // 根据id查询企业
      async handleClick (tab, event) {
        if (tab.name === 'second') {
          this.formData = await getenterpriseIdAPI(this.companyId)
        }
      },
      // 新增按钮
      addRole () {
        this.editorForm = {
          name: '',
          description: ''
        }
        this.is_add = true,
          this.dialogFormVisible = true
      },
      // 每页显示的条数发生改变时触发
      handleSizeChange (val) {
        this.query.pagesize = val
        this.paging()
      },

      // 当前页面发生改变时触发
      handleCurrentChange (val) {
        this.query.page = val
        this.paging()
        const start = (val - 1) * this.query.pagesize
        const end = this.query.pagesize * val
        this.nowRolesList = this.rolesList.slice(start, end)
      },

      // 编辑角色
      async editRoles (row) {
        this.loading = true
        this.is_add = false
        // 获取要编辑员工的信息
        this.editorForm = await getRoleIdAPI(row.id)
        this.dialogFormVisible = true
        this.loading = false
      },
      // 取消按钮
      btnCanCel () {
        this.editorForm = {
          name: '',
          description: ''
        }
        this.dialogFormVisible = false
        this.$refs.formName.resetFields()
      },
      // 确定按钮
      btnSubmit () {
        this.$refs.formName.validate(async is_ok => {
          if (is_ok) {
            if (this.is_add) {
              await addRoleAPI(this.editorForm)
              this.getRoles()
              this.$message.success('新增成功')
              this.dialogFormVisible = false
            } else {
              await updateRoleAPI(this.editorForm)
              this.getRoles()
              this.dialogFormVisible = false
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },
      // 删除角色
      delRoles (row) {
        this.$confirm("您确认要删除吗?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        }).then(async () => {
          if (this.nowRolesList.length === 1) {
            this.query.page--
            if (this.query.page === 0) {
              this.query.page = 1
            }
          }
          await deleteRoleAPI(row.id)
          this.getRoles()
          this.$message.success('删除成功')
        })
      },
      // 分页
      paging () {
        this.nowRolesList = this.rolesList.slice((this.query.page - 1) * this.query.pagesize, this.query.page * this.query.pagesize)
      }
    }
  } 
</script>

<style lang="scss" scoped>
  .box-card {
    padding: 10px 30px;
  }

  .tab-pane {
    padding: 20px;
  }

  .el-pagination {
    text-align: center;
    margin-top: 20px;
  }
</style>